﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Mail;
using System.Net;
using System.Net.Configuration;
using System.Web.Security;
using System.Web;
using System.Drawing.Imaging;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Collections.Specialized;

namespace HolcimProject.Common
{
    public class Utilities
    {


        /// <summary>
        /// Check user exits in group
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <param name="groupName"></param>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public static bool CheckUserExitsInGroup(string siteUrl, string groupName, string loginName)
        {
            SPUserCollection users = GetAllUserInGroup(siteUrl, groupName);
            if(users!=null)
            {
                foreach (SPUser user in users)
                {
                    if (user.LoginName.ToUpper() == loginName.ToUpper())
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        

        /// <summary>
        /// Get SharePoint group by name
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public static SPGroup getGroupByName(string siteUrl, string groupName)
        {
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    foreach (SPGroup group in web.SiteGroups)
                    {
                        if (group.Name == groupName)
                        {
                            return group;
                        }
                    }
                }
                return null;
            }
        }

        /// <summary>
        /// Get item by id
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <param name="listName"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static SPListItem GetItemByID(string siteUrl, string listName, int id)
        {
            using (SPSite spSite = new SPSite(siteUrl))
            {
                Microsoft.SharePoint.SPList spList = spSite.OpenWeb().Lists[listName];
                SPListItem item = spList.GetItemById(id);
                return item;
            }
        }


        /// <summary>
        /// Get user by ID
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static SPUser getUserByID(string siteUrl, int id)
        {
            SPUser user = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteUrl))
                {
                    user = site.OpenWeb().AllUsers.GetByID(id);
                }
            });
            return user;
        }

        /// <summary>
        /// Send email using SpUtility
        /// </summary>
        /// <param name="web"></param>
        /// <param name="header"></param>
        /// <param name="mailBody"></param>
        public static void SendEmail(SPWeb web, StringDictionary header, string mailBody)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPUtility.SendEmail(web, header, mailBody);
            });
        }

        /// <summary>Get current user
        /// 
        /// </summary>
        /// <returns>SPUser</returns>
        public static SPUser GetCurrentUser(string siteUrl)
        {

            SPContext currentContext = SPContext.Current;
            string uName = string.Empty;

            if (currentContext != null && currentContext.Web.CurrentUser != null)
            {
                SPWeb web = currentContext.Web;
                return web.CurrentUser;
            }
            if (new SPSite(siteUrl).OpenWeb().CurrentUser != null)
            {
                return new SPSite(siteUrl).OpenWeb().CurrentUser;
            }
            return null;
        }
        /// <summary>get all users in sharepoint group
        /// 
        /// </summary>
        /// <param name="site">URL sharepoint site</param>
        /// <param name="group">Name sharepoint group</param>
        /// <returns></returns>
        public static SPUserCollection GetAllUserInGroup(string site, string group)
        {
            try
            {
                SPUserCollection _Users = null;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPGroupCollection _Groups = GetAllGroupInSite(site);
                    foreach (SPGroup _Group in _Groups)
                    {
                        if (_Group.Name.ToString().Equals(group))
                        {
                            _Users = _Group.Users;
                            break;
                        }
                    }
                });
                return _Users;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>get all group in sharepoint site
        /// 
        /// </summary>
        /// <param name="site">Url sharepoint site</param>
        /// <returns></returns>
        public static SPGroupCollection GetAllGroupInSite(string site)
        {
            try
            {
                SPGroupCollection _Groups = null;
                using (SPSite _Site = new SPSite(site))
                {
                    using (SPWeb _Web = _Site.OpenWeb())
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            _Groups = _Web.SiteGroups;
                        });
                        return _Groups;

                    }

                }
            }
            catch
            {
                throw;
            }
        }

        /// <summary>Get data return SPListItemCollection using CAML query
        /// 
        /// </summary>
        /// <param name="strSite"></param>
        /// <param name="strList"></param>
        /// <param name="strQuery"></param>
        /// <returns></returns>     
        public static SPListItemCollection GetDataInSharePointList(string site, string list, string query)
        {
            try
            {
                SPListItemCollection _Items = null;
                using (SPSite _Site = new SPSite(site))
                {
                    using (SPWeb _Web = _Site.OpenWeb())
                    {

                        SPList _List = _Web.Lists[list];
                        SPQuery _Query = new SPQuery();
                        _Query.Query = query;
                        _Query.ViewAttributes = "Scope='RecursiveAll'";
                        _Items = _List.GetItems(_Query);
                        return _Items;
                    }

                }
            }
            catch
            {
                throw;
            }
        }

        /// <summary>Get List by name
        /// 
        /// </summary>
        /// <param name="ListName"></param>
        /// <returns></returns>       
        public static SPList GetList(string siteUrl, string ListName)
        {
            try
            {
                // get current site
                using (SPSite _site = new SPSite(siteUrl))
                {
                    //return SPlist by name
                    return _site.OpenWeb().Lists[ListName];
                }
            }
            catch
            {
                return null;
            }
        }

        public static SPList GetListByDisplayName(string siteUrl, string ListName)
        {
            SPList list;
            try
            {
                // get current site
                using (SPSite _site = new SPSite(siteUrl))
                {
                    using (SPWeb oWeb = _site.OpenWeb())
                    {

                        list = oWeb.Lists[ListName];
                        list.EnableModeration = true;

                    }
                }
                return list;
            }
            catch
            {
                return null;
            }
        }

        public static SPList GetListByStaticName(string siteUrl, string ListName)
        {
            SPList list;
            try
            {
                // get current site
                using (SPSite _site = new SPSite(siteUrl))
                {
                    using (SPWeb oWeb = _site.OpenWeb())
                    {

                        list = oWeb.GetList(ListName);
                        list.EnableModeration = true;

                    }
                }
                return list;
            }
            catch
            {
                return null;
            }
        }


        public static void recursivewebcheck(SPWeb oSPweb)
        {

            foreach (SPWeb web in oSPweb.Webs)
            {
                SPList list = web.GetList("PublishingImages");
                list.EnableModeration = true; web.Dispose();
                if (oSPweb.Webs.Count > 0)
                {
                    recursivewebcheck(web);
                }
                web.Dispose();
            }

        }



        private static MailMessage BuildMailMessage(string ADMIN_MAIL_NAME, string fromAddress, string toAddress, string subject, string body)
        {
            MailMessage message = new MailMessage
            {
                From = new MailAddress(fromAddress, ADMIN_MAIL_NAME),
                Subject = subject,
                Body = body,
                BodyEncoding = Encoding.UTF8,
                IsBodyHtml = true
            };

            string[] tos = toAddress.Split(';');
            foreach (string to in tos)
                message.To.Add(new MailAddress(to));

            return message;
        }

        /// <summary>
        /// Creates the random password.
        /// </summary>
        /// <param name="PasswordLength">Length of the password.</param>
        /// <returns></returns>
        public static string CreateRandomCode(int PasswordLength)
        {
            string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
            //string _allowedChars = _allowedChars;
            Random randNum = new Random();
            char[] chars = new char[PasswordLength];
            int allowedCharCount = _allowedChars.Length;

            for (int i = 0; i < PasswordLength; i++)
            {
                chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
            }

            return new string(chars);
        }

        public static MembershipUser GetUserByName(string username)
        {
            MembershipUser value = null;
            try
            {
                MembershipUserCollection users = Membership.GetAllUsers();
                if (users != null && users.Count > 0)
                    value = users[username];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return value;
        }


        public static String GetStringFromResourceFile(String key, uint language)
        {
            if (String.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Utilities.GetStringFromResourceFile(key, language) requires key.");
            }

            String fileName = key.Split(':')[1].ToString().Split(',')[0].ToString();
            String keyName = key.Split(':')[1].ToString().Split(',')[1].ToString();
            String returnValue = GetStringFromResourceFile(fileName, keyName, language);

            if (String.IsNullOrEmpty(returnValue) || returnValue.Equals(key) || returnValue.Equals(key + ";"))
            {
                throw new SPException("Resource key " + key + " is missing a resource value.");
            }

            return returnValue;
        }

        /// <summary>
        /// Gets the string from resource file.
        /// </summary>
        /// <param name="resourceFileName">The resource file name.</param>
        /// <param name="keyName">The resource string key name.</param>
        /// <param name="language">The language ID.</param>
        /// <returns>Resource string value</returns>
        private static String GetStringFromResourceFile(String resourceFileName, String keyName, uint language)
        {
            if (String.IsNullOrEmpty(resourceFileName))
            {
                throw new Exception("Utilities.GetStringFromResourceFile() requires resourceFileName parameter.");
            }
            if (String.IsNullOrEmpty(keyName))
            {
                throw new Exception("Utilities.GetStringFromResourceFile() requires keyName parameter.");
            }

            String returnValue = null;

            try
            {
                returnValue = SPUtility.GetLocalizedString("$Resources:" + resourceFileName + "," + keyName, resourceFileName, language);
            }
            catch (NullReferenceException)
            {
                throw new NullReferenceException("Resource string is not available.");
            }

            return returnValue;
        }



        public bool PreventHtmlInput(string value)
        {
            string htmlTags = GetStringFromResourceFile("halfHtmlTags", SPContext.Current.Web.Language);
            string regEx = @"<[\w]+>";
            string[] halfHtmlTags = htmlTags.Split('|');
            bool isValid = !System.Text.RegularExpressions.Regex.IsMatch(value, regEx);
            if (isValid)
            {
                foreach (string halfHtmlTag in halfHtmlTags)
                {
                    if (value.IndexOf(halfHtmlTag) > 0)
                    {
                        isValid = false;
                        break;
                    }
                }
            }
            return isValid;
        }
    }
}
